package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;

import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    /**
     * 根据数据id查询子数据列表
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getParentId,id);
        List<Dict> dictList = baseMapper.selectList(lambdaQueryWrapper);
        for (Dict dict:dictList){
            Long dictId = dict.getId();
            boolean children = isChildren(dictId);
            dict.setHasChildren(children);
        }
        return dictList;
    }

    /**
     * 导出字典数据
     * @param response
     */
    @Override
    public void exportDictData(HttpServletResponse response)  {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode("数据字典", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictEeVoList = new ArrayList<>();
        for (Dict dict :dictList){
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictEeVoList.add(dictEeVo);
        }
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入字典数据
     * @param file
     */
    @Override
    @CacheEvict(value = "dict",allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，直接根据value查询
        if (StringUtils.isEmpty(dictCode)){
            //根据value查询
            LambdaQueryWrapper<Dict> lambdaQueryWrapper  =new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Dict::getValue,value);
            Dict dict = baseMapper.selectOne(lambdaQueryWrapper);
            return dict.getName();
        }else {
            //如果dictCode不为空，直接根据value和dictCode查询
            LambdaQueryWrapper<Dict> lambdaQueryWrapper  =new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Dict::getDictCode,dictCode);
            Dict dict = baseMapper.selectOne(lambdaQueryWrapper);
            Long parent_id = dict.getId();
            Dict finalDict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getValue,value)
                    .eq(Dict::getParentId,parent_id));
            return finalDict.getName();
        }
    }

    //根据dictCode获取下一个节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictcode获取对应id
        LambdaQueryWrapper<Dict> lambdaQueryWrapper  =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getDictCode,dictCode);
        Dict dict = baseMapper.selectOne(lambdaQueryWrapper);
        //根据id获取子节点
        List<Dict> childData = this.findChildData(dict.getId());
        return childData;
    }

    //判断id下面是否有子节点
    private boolean isChildren(Long id){
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getParentId,id);
        Integer count = baseMapper.selectCount(lambdaQueryWrapper);
        return count>0;
    }
}
